package com.example.jetpacktest.network

import com.example.jetpacktest.network.service.FstApi
import com.google.gson.GsonBuilder
import kotlinx.coroutines.*
import org.junit.Test
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
import java.util.*
import kotlin.coroutines.resume

class Test001 {

    private val url: String = "http://www.hbjsinfo.com:9050/RealTimeDataQuery/"

    @Test
    fun test001(){
        val gson = GsonBuilder()
            .registerTypeAdapter(Date::class.java, DateDeserializer())
            .registerTypeAdapter(Float::class.javaObjectType, FloatDeserializer())
            .registerTypeAdapter(Float::class.javaPrimitiveType, FloatDeserializer())
            .create()
        val retrofit = Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create(gson)).build()
        val fstApi = retrofit.create(FstApi::class.java)
        runBlocking {
            try{
                val fstData: FstData = getFstData(fstApi)
                println(fstData)
            }catch (ex: Exception){
                println("ex = $ex")
                ex.printStackTrace()
            }

            println("do other things")
        }
    }

    private suspend fun getFstData(fstApi: FstApi): FstData{
        return withContext(Dispatchers.IO){
            fstApi.getFstData(1, 100, 115001)
        }
    }


    @Test
    fun test002(){
        runBlocking {
            //使用suspendCancellableCoroutine()挂起协程的话，必须手动去恢复
            val x = suspendCancellableCoroutine{c: CancellableContinuation<Int> ->
                c.invokeOnCancellation { ex ->
                    println("$ex")
                }
                println("start work")
                Thread.sleep(5000)
                println("end work")
                c.resume(101) //手动恢复
            }
            println("after suspend....x = $x")
        }
    }


    @Test
    fun test003(){
        runBlocking {
            launch {
                println("start work")
                delay(1000)
                println("end work")
            }
        }
    }


}